package com.alkaid.manga.service.impl;

import com.alkaid.commons.entity.Manga;
import com.alkaid.commons.entity.MangaDetails;
import com.alkaid.commons.entity.MangaSource;
import com.alkaid.commons.ex.DataNotFoundException;
import com.alkaid.manga.mapper.MangaDetailsMapper;
import com.alkaid.manga.mapper.MangaMapper;
import com.alkaid.manga.service.MangaDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.alkaid.commons.msg.DataTypeEnum.MANGA;
import static com.alkaid.commons.msg.DataTypeEnum.MANGA_DETAIL;

/**
 * @author Kylin
 */
@Service
public class MangaDetailsServiceImpl implements MangaDetailsService {

    private final MangaMapper mangaMapper;

    private final MangaDetailsMapper mangaDetailsMapper;

    public MangaDetailsServiceImpl(MangaMapper mangaMapper, MangaDetailsMapper mangaDetailsMapper) {
        this.mangaMapper = mangaMapper;
        this.mangaDetailsMapper = mangaDetailsMapper;
    }

    @Override
    public List<MangaSource> getSource(Long id) throws DataNotFoundException {
        List<MangaSource> text = mangaDetailsMapper.findSource(id);
        if (text == null) {
            throw new DataNotFoundException(MANGA_DETAIL);
        }
        return text;
    }

    @Override
    public Manga getMangaDetailsWithDetailId(Long id) throws DataNotFoundException {
        List<MangaDetails> mangaDetails = mangaDetailsMapper.findSameMangaIdById(id);
        if (mangaDetails.size() == 0) {
            throw new DataNotFoundException(MANGA_DETAIL);
        }
        Integer mangaId = mangaDetails.get(0).getMangaId();
        Manga manga = mangaMapper.findById(mangaId);
        if (manga == null) {
            throw new DataNotFoundException(MANGA);
        }
        manga.setAuthor(mangaDetailsMapper.findAuthors(mangaId));
        manga.setMangaDetails(mangaDetails);
        return manga;
    }
}
